import cgi
import datetime
import logging
import wsgiref.handlers

from operator import itemgetter

from google.appengine.ext import webapp
from google.appengine.ext import db 
from google.appengine.api import memcache


class UserMessage(db.Model):
  user_id = db.StringProperty()
  band = db.StringProperty()
  message = db.StringProperty()
  time_left = db.IntegerProperty()


class HistoricalUserMessage(db.Model):
  user_id = db.StringProperty()
  band = db.StringProperty()
  message = db.StringProperty()
  time_left = db.IntegerProperty()


class MainPage(webapp.RequestHandler):
  def get(self):
    upcoming_user_messages = db.GqlQuery(
        "SELECT * FROM UserMessage ORDER BY time_left DESC")
    upcoming_user_messages_table = ""
    for user_message in upcoming_user_messages:
      upcoming_user_messages_table = (upcoming_user_messages_table + "<tr><td>" +
          str(user_message.time_left) + "</td><td>" + user_message.user_id +
          "</td><td>" + user_message.band + "</td><td>" + user_message.message +
          "</td></tr>\n")

    historical_user_messages = db.GqlQuery(
        "SELECT * FROM HistoricalUserMessage ORDER BY time_left ASC")
    historical_user_messages_table = ""
    for user_message in historical_user_messages:
      historical_user_messages_table = (historical_user_messages_table +
          "<tr><td>" + str(user_message.time_left) + "</td><td>" +
          user_message.user_id + "</td><td>" + user_message.band + "</td><td>" +
          user_message.message + "</td></tr>\n")

    fyffest = datetime.datetime(2011, 8, 3, 12, 0, 0)
    now = datetime.datetime.today()
    diff = fyffest - now
    diff_seconds = diff.days * 24 * 3600 + diff.seconds

    self.response.out.write("""
        <html>
          <head>
            <title>FYFFest engine status</title>
          </head>
          <body>
            <h1>FYFFest engine status</h1>
            time left: """ + str(diff_seconds) + """
            <h2>Upcoming messages</h2>
            <table>
              <tr>
                <td>time left</td>
                <td>user id</td>
                <td>chosen band</td>
                <td>message</td>
              </tr>""" + upcoming_user_messages_table + """
            </table>
            <h2>Historical messages</h2>
            <table>
              <tr>
                <td>time left</td>
                <td>user id</td>
                <td>chosen band</td>
                <td>message</td>
              </tr>""" + historical_user_messages_table + """
            </table>
          </body>
        </html>""")


class GetLatestMessage(webapp.RequestHandler):
  def post(self):
    fyffest = datetime.datetime(2011, 8, 3, 12, 0, 0)
    now = datetime.datetime.today()
    diff = fyffest - now
    diff_seconds = diff.days * 24 * 3600 + diff.seconds

    last_message = None
    user_messages = db.GqlQuery(
        "SELECT * FROM UserMessage ORDER BY time_left DESC")
    for user_message in user_messages:
      if user_message.time_left < diff_seconds:
        if not last_message:
          self.response.out.write("nobody,The Descendents,no messages exist!")
          return
        else:
          self.response.out.write(last_message.user_id + "," +
              last_message.band + "," + last_message.message)
          return
      else:
        if last_message:
          # move last message to historical table and delete
          historical_user_message = HistoricalUserMessage()
          historical_user_message.time_left = last_message.time_left
          historical_user_message.user_id = last_message.user_id
          historical_user_message.band = last_message.band
          historical_user_message.message = last_message.message
          historical_user_message.put()
          last_message.delete()
        last_message = user_message
    if last_message:
      self.response.out.write(last_message.user_id + "," +
          last_message.band + "," + last_message.message)
      return
    self.response.out.write("nobody,The Descendents,no messages exist!")

  def get(self):
    self.post()


class AddMessage(webapp.RequestHandler):
  def post(self):
    fyffest = datetime.datetime(2011, 8, 3, 12, 0, 0)
    now = datetime.datetime.today()
    diff = fyffest - now
    time_left = diff.days * 24 * 3600 + diff.seconds

    now = self.request.get("now")
    time_left_string = self.request.get("time_left")
    if not time_left_string and not now:
      self.response.out.write("NO,Error: No time was given for the message.")
      return
    if time_left_string and not now:
      time_left = int(time_left_string)
    user_id = self.request.get("user_id")
    if not user_id:
      self.response.out.write("NO,Error: No user was given for the message.")
      return
    band = self.request.get("band")
    if not band:
      self.response.out.write("NO,Error: No band was set for the message.")
      return
    message = self.request.get("message")
    if not message:
      self.response.out.write("NO,Error: No message was set.")
      return
    
    # verify the time_left parameter is valid
    user_message = UserMessage()
    user_message.time_left = time_left
    user_message.user_id = user_id
    user_message.band = band
    user_message.message = message
    user_message.put()
    self.response.out.write("OK")

  def get(self):
    self.post()


class GetStatistics(webapp.RequestHandler):
  def post(self):
    fyffest = datetime.datetime(2011, 8, 3, 12, 0, 0)
    now = datetime.datetime.today()
    diff = fyffest - now
    time_left = diff.days * 24 * 3600 + diff.seconds

    band_time = {}
    total_time = 0

    current_user_message = db.GqlQuery(
        "SELECT * FROM UserMessage ORDER BY time_left DESC LIMIT 1")
    if not current_user_message[0]:
      self.response.out.write("no messages")
      return
    band = current_user_message[0].band
    time_increment = current_user_message[0].time_left - time_left
    total_time = total_time + time_increment
    band_time[band] = band_time.get(band, 0) + time_increment

    historical_user_messages = db.GqlQuery(
        "SELECT * FROM HistoricalUserMessage ORDER BY time_left ASC")
    last_message = current_user_message[0]
    for user_message in historical_user_messages:
      band = user_message.band
      time_increment = user_message.time_left - last_message.time_left
      total_time = total_time + time_increment
      band_time[band] = band_time.get(band, 0) + time_increment
      last_message = user_message

    band_percentages_table = ""
    sorted_band_time = sorted(band_time.iteritems(), key=itemgetter(1),reverse=True)
    for band_count in sorted_band_time:
      band_percentages_table = (band_percentages_table + band_count[0])
      band_percentages_table = (band_percentages_table + "," + str(band_count[1]))
      band_percentages_table = (band_percentages_table + "," +
          str(band_count[1] / float(total_time)) + "\n")

    self.response.out.write(band_percentages_table)

  def get(self):
    self.post()

def main(): 
  application = webapp.WSGIApplication([('/', MainPage),
                                        ('/get_latest_message', GetLatestMessage),
                                        ('/add_message', AddMessage),
                                        ('/get_stats', GetStatistics)], 
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
